from django.shortcuts import render, redirect
from users.models import MajorSelection, LotteryResultModel, CustomUser
from django.http import JsonResponse
import random


def home_view(request):
    """主页视图"""
    if not request.user.is_authenticated:
        return redirect('users:login')

    majors_select = MajorSelection.objects.filter(user=request.user)  # 这里使用 user.id
    return render(request, 'home/home.html', {'user': request.user, 'majors1': majors_select})


def lottery_view(request):
    """抽签逻辑视图"""
    if not request.user.is_authenticated:
        return redirect('users:login')

    if request.method == "POST":
        # 使用 .get() 方法来获取 major_id
        major_id = request.POST.get("major_id")
        user = request.user

        # 根据 major_id 查找 MajorSelection
        user_id = request.user.id
        majors_select = MajorSelection.objects.get(major_id=major_id, user_id=user_id)

        print(f'当前剩余次数{majors_select.num}')
        res_id = -99
        if majors_select.num > 0:
            majors_select.num -= 1

            start = majors_select.major.start
            end = majors_select.major.end

            res_id = random.randint(start, end)  # [start,end]

            count = 0
            while LotteryResultModel.objects.filter(index_num=res_id).exists():
                res_id = random.randint(start, end)
                count += 1

                if count > 100:
                    print("抽签系统出错")
                    data = {
                        'res_id': -99,
                    }
                    return JsonResponse(data, status=250)

            LotteryResultModel.objects.create(
                user=user,
                index_num=res_id,
                major_id=major_id,
            )

            # 更新 CustomUser 的 result_list 字段
            user = request.user  # 获取当前登录的用户
            if user.result_list == "还未抽签":
                user.result_list = f"{majors_select.major.name}--{res_id}"  # 第一次抽签，直接赋值
            else:
                # 如果已经有抽签记录，将新结果添加到现有记录中
                user.result_list += f",{majors_select.major.name}--{res_id}"

            user.save()  # 保存更新后的用户记录
            majors_select.save()

        data = {
            'res_id': res_id,
            'remaining_attempts': majors_select.num,
        }
        return JsonResponse(data)
        # return render(request, 'home/home.html', {'majors_select': majors_select,'ans':res_id})

    return JsonResponse({"error": "非法请求"}, status=400)


from users.models import CustomUser


def show_view(request):
    if not request.user.is_authenticated:
        return redirect('users:login')

    if request.method == "GET":
        result_list = LotteryResultModel.objects.filter(user=request.user)

        ans_list = []
        if result_list:
            for result in result_list:
                ans_list.append({
                    'major': f"{result.major.name} - {result.major.get_level_display()}组",
                    'res_id': result.index_num,
                })

        context = {
            "ans_list": ans_list,
            'user': CustomUser.objects.get(id=request.user.id),
        }

        return render(request, 'home/show.html', context)
